<?php

namespace App\Http\Controllers\Customer;

use App\Http\Controllers\Controller;
use App\Http\Requests\service\AbnormalRequest;
use App\Models\OrderModel;
use App\Models\service\AbnormalConfigModel;
use App\Models\service\AbnormalModel;
use App\Models\service\ProblemModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Abnormal extends Controller
{
    use AbnormalRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $auth = $request->get('auth');
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $order_sn = $request->input('order_sn', '');
        $des_country_id = $request->input('des_country_id', '');
        $order_status = $request->input('order_status', '');
        $status = $request->input('status', '');
        $type = $request->input('type', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = AbnormalModel::query()->with('mode')->withWhereHas('order', function ($query) use ($order_sn, $des_country_id, $order_status) {
            $query->with(['customer', 'des_country', 'take_order']);
            if($order_sn){
                $query->where('sn', $order_sn);
            }
            if($des_country_id){
                $query->where('des_country_id', $des_country_id);
            }
            if($order_status){
                $query->where('status', $order_status);
            }
        })->where('customer_id', $auth->id);

        if($status){
            $query = $query->where('status', $status);
        }

        if($type){
            $query = $query->where('type', $type);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
//                'customer_name' => $item->order->customer ? $item->order->customer->name : '',
//                'customer_sn' => $item->order->customer ? $item->order->customer->sn : '',
                'order_sn' => $item->order ? $item->order->sn : '',
                'take_order_sn' => $item->order->take_order ? $item->order->take_order->sn : '',
                'des_country_name' => $item->order->airport->country_name ?? '',
                'type' => $item->type,
                'type_name' => AbnormalModel::TYPE[$item->type],
                'abnormal_desc' => $item->abnormal_desc,
                'status' => $item->status,
                'status_text' => AbnormalModel::STATUS[$item->status],
                'handle_mode' => $item->mode ? $item->mode->name : '',
                'remarks' => $item->remarks,
                'created_at' => $item->created_at->toDateTimeString()
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }


    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();
        $ids = $request->input('id', '');
        $ids = explode(',', $ids);

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                $find_order = OrderModel::find($id);
                if(!$find_order){
                    return $this->error('入仓单不存在');
                }

//                if(!$find_order->take_order_id){
//                    return $this->error('没有航班信息不能异常反馈');
//                }

                $model = new AbnormalModel();
                $model->order_id = $id;
                $model->take_order_id = $find_order->take_order_id;
                $model->customer_id = $auth->id;
                $model->type = $params['type'];
                $model->abnormal_desc = $params['abnormal_desc'];
                $model->file = json_encode($params['file']);
                $model->handle_desc = $params['handle_desc'] ?? '';
                $model->source = 1;
                $model->save();

                $find_order->is_exception = 1;
                $find_order->save();
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }


    public function delete(int $id){
        $model = AbnormalModel::find($id);
        if(!$model) {
            return $this->error('记录不存在');
        }

        $order = OrderModel::find($model->order_id);

        $order->is_exception = 0;
        $order->save();

        $model->delete();
        return $this->success();
    }

    /**
     * Notes:详情
     * User: xiangzi
     * Date: 2024/9/26
     * Time: 16:00
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        $id = intval($request->input('id', 0));
        $model = AbnormalModel::with('mode')->find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $return = [
            'base_Info' => [
                'abnormal_time' => $model->created_at->toDateTimeString(),
                'status_text' => AbnormalModel::STATUS[$model->status],
                'abnormal_desc' => $model->abnormal_desc,
                'handle_desc' => $model->handle_desc,
                'type_name' => AbnormalModel::TYPE[$model->type],
                'file' => json_decode($model->file, true),
            ]
        ];


        $return['handle_info'] = [];

        $return['handle_info'][] = [
            'time' => $model->created_at->toDateTimeString(),
            'desc' => '反馈异常',
        ];

        if($model->start_time){
            $return['handle_info'][] = [
                'time' => $model->start_time,
                'desc' => '开始处理'
            ];
        }

        if($model->end_time){
            $mode = $model->mode->name ?? '';
            $return['handle_info'][] = [
                'time' => $model->end_time,
                'desc' => '处理完成  ' . '处理方式：' . $mode . '，处理备注：' . $model->remarks,
            ];
        }

        if($model->turn_time) {
            $return['handle_info'][] = [
                'time' => $model->turn_time,
                'desc' => '转问题件'
            ];
        }

        return $this->success($return);
    }


}
